/* -----------------
* brief
* 1. this is code gen by tools
* 2. mvc code are driver by the model defined with the same filename,
	 for example:
	 there is a Xmodel struct define in xmodel.go file, after the script run (lego model-mvc module_name xmodel)
     it will auto create the code under the module's path
	 m --> xmodel.go
	 v --> view
	 c --> xmodel_ctrl
* 3. you should modify this code if it doesn't satisfy your purpose
*/

package controller

import (
	"encoding/json"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"github.com/valyala/fasthttp"
	"saas_sys_base/common"
	"saas_sys_base/common/err_const"

	. "saas_sys_base/modules/eshop/models"
	. "saas_sys_base/modules/eshop/service"
	. "saas_sys_base/modules/tenant/service"
	. "saas_sys_base/modules/user/service"
)

type EShopCtrl struct {
	service       EShopService
	wxUserservice WxUserService
	tenantService TenantService
}

func init() {
	vc := new(EShopCtrl)
	_ctrlList = append(_ctrlList, vc)
}

func (vc *EShopCtrl) CtrlInfo() string {
	return "EShopCtrl"
}

func (vc *EShopCtrl) RoutInit() {
	// 列表页面
	lego.GET("/admin/EShop/listpage", vc.ListPage, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/EShop/listjson", vc.ListJson, lego.LEGO_SESSION_TYPE_ADMIN, true)
	// 编辑页面
	lego.GET("/admin/EShop/editpage", vc.GetEditPage, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.POST("/admin/EShop/editpage", vc.PostEditPage, lego.LEGO_SESSION_TYPE_ADMIN, true)
	// 删除
	lego.POST("/admin/EShop/del", vc.DelRecode, lego.LEGO_SESSION_TYPE_ADMIN, true)
	//审核
	lego.POST("/admin/EShop/check", vc.CheckShop, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.POST("/admin/EShop/uncheck", vc.UnCheckShop, lego.LEGO_SESSION_TYPE_ADMIN, true)

	//店铺注册
	lego.APIPOST("/api/EShop/register", vc.Register, true)

	//获取租户店铺列表
	lego.GET("/admin/EShop/getShopForSelectByTenand", vc.GetShopForSelectByTenand, lego.LEGO_SESSION_TYPE_WEB, true)

	lego.APIGET("/api/EShop/getShopForSelectByTenand", vc.GetShopForSelectByTenand, true)
	lego.APIGET("/api/EShop/getShopForTenand", vc.GetShopForTenand, true)
}

/* 列表接口
* params:
  ---
*/
func (vc *EShopCtrl) ListJson(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := ""
	for {
		// 表单校验
		type ReqParams struct {
			Keyword string // 关键字查询
			Page    int    `vd:"$>=0"` // 分页
			PSize   int    `vd:"$>0"`  // 分页大小
		}
		req := ReqParams{
			Keyword: string(ctxExt.Peek("keyword")),
			Page:    utils.BytesToInt(ctxExt.Peek("page")),
			PSize:   utils.BytesToInt(ctxExt.Peek("limit")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		// 业务查询
		if list, total, err := vc.service.ListEShop(req.Keyword, req.Page, req.PSize); err != nil {
			lego.LogError(err)
		} else {
			response["count"] = total
			response["data"] = list
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *EShopCtrl) ListPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		break
	}
	ctxExt.HTML("eshop/view/EShop/list.html", data)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *EShopCtrl) GetEditPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		type ReqParams struct {
			Id int64 // 记录id，为空则新建，否则为编辑
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}
		target := vc.service.GetEShopById(req.Id)
		data["detail"] = target
		break
	}
	ctxExt.HTML("eshop/view/EShop/edit.html", data)
	return
}

/* 数据编辑
* params:
  ---
*/
func (vc *EShopCtrl) PostEditPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	data := make(map[string]interface{})

	code := 0
	msg := ""

	for {
		// 表单校验
		type ReqParams struct {
			//#ModelEditFormDefined#
			Id       int64 `vd:""`
			ShopName string
			Province string
			City     string
			Area     string
			Address  string
			Mobile   string
			CateId   int64
			License  string
			Lat      float64
			Lng      float64
		}
		req := ReqParams{
			//#ModelEditFormFiled#
			Id:       utils.BytesToInt64(ctxExt.Peek("id")),
			ShopName: string(ctxExt.Peek("shop_name")),
			Province: string(ctxExt.Peek("province")),
			City:     string(ctxExt.Peek("city")),
			Area:     string(ctxExt.Peek("area")),
			Address:  string(ctxExt.Peek("address")),
			Mobile:   string(ctxExt.Peek("mobile")),
			CateId:   utils.BytesToInt64(ctxExt.Peek("cate_id")),
			License:  string(ctxExt.Peek("license")),
			Lat:      utils.BytesToFloat64(ctxExt.Peek("lat")),
			Lng:      utils.BytesToFloat64(ctxExt.Peek("lng")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		// 业务处理
		recode := vc.service.GetEShopById(req.Id)
		if recode == nil {
			// 新建
			recode := new(EShop)
			//#ModelFiledMapper#'
			recode.Id = req.Id
			recode.Province = req.Province
			recode.City = req.City
			recode.Area = req.Area
			recode.Address = req.Address
			recode.Mobile = req.Mobile
			recode.CateId = req.CateId
			recode.License = req.License
			recode.Lat = req.Lat
			recode.Lng = req.Lng
			recode.ShopName = req.ShopName

			if false == vc.service.SaveEShop(recode) {
				code = 100
				msg = "false"
				break
			}
		} else {
			//#ModelFiledMapper#
			recode.Id = req.Id
			recode.Province = req.Province
			recode.City = req.City
			recode.Area = req.Area
			recode.Address = req.Address
			recode.Mobile = req.Mobile
			recode.CateId = req.CateId
			recode.License = req.License
			recode.Lat = req.Lat
			recode.Lng = req.Lng
			recode.ShopName = req.ShopName

			if false == vc.service.UpdateEShop(recode) {
				code = 100
				msg = "false"
				break
			}
		}
		break
	}
	response["code"] = code
	response["msg"] = msg
	response["data"] = data
	ctxExt.JSON(200, response)
	return
}

/* 删除数据记录
* params:
  ---
*/
func (vc *EShopCtrl) DelRecode(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	data := make(map[string]interface{})

	code := 0
	msg := ""
	for {
		// 表单校验
		type ReqParams struct {
			Id int64 `vd:"$>0"` // 记录id
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}
		// 业务删除
		target := vc.service.GetEShopById(req.Id)
		if target == nil {
			code = 100
			msg = "记录不存在"
			break
		}

		if false == vc.service.DelEShopById(target.Id) {
			code = 100
			msg = "操作失败"
			break
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	response["data"] = data
	ctxExt.JSON(200, response)
	return
}

func (vc *EShopCtrl) CheckShop(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	data := make(map[string]interface{})

	code := 0
	msg := ""

	for {
		// 表单校验
		type ReqParams struct {
			Id int64 `vd:"$>0"` // 记录id
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}

		// 业务处理
		recode := vc.service.GetEShopById(req.Id)
		if recode == nil {
			code = 100
			msg = "记录不存在"
			break
		}

		recode.IfCheck = 1
		if false == vc.service.UpdateEShop(recode) {
			code = 100
			msg = "false"
			break
		}

		vc.tenantService.UpdateRegisterState(recode.TenantId, common.REG_STATE_CHECK_PASS)

		break
	}

	response["code"] = code
	response["msg"] = msg
	response["data"] = data
	ctxExt.JSON(200, response)
	return
}

func (vc *EShopCtrl) UnCheckShop(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	data := make(map[string]interface{})

	code := 0
	msg := ""

	for {
		// 表单校验
		type ReqParams struct {
			Id int64 `vd:"$>0"` // 记录id
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}

		// 业务处理
		recode := vc.service.GetEShopById(req.Id)
		if recode == nil {
			code = 100
			msg = "记录不存在"
			break
		}

		recode.IfCheck = -1
		if false == vc.service.UpdateEShop(recode) {
			code = 100
			msg = "false"
			break
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	response["data"] = data
	ctxExt.JSON(200, response)
	return
}

func (vc *EShopCtrl) Register(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})

	code := 0
	msg := ""

	for {
		//先检测sys token
		//type HeaderParam struct {
		//	Token     string
		//	Timestamp string
		//	LoginMode int
		//	AppToken  string
		//}
		//
		//var headerparam = &HeaderParam{
		//	Token:     string(ctxExt.Request.Header.Peek("token")),
		//	Timestamp: string(ctxExt.Request.Header.Peek("timestamp")),
		//	AppToken: string(ctxExt.Request.Header.Peek("apptoken")),
		//}

		sessionData := common.GetSessionData(&ctxExt)
		appwho := sessionData.AppTokenWho

		// TODO 后续考虑还需要check sys token吗？
		//userwho, _, err := vc.wxUserservice.CheckToken(headerparam.Token, headerparam.Timestamp)
		//if err != nil {
		//	ctxExt.ResponseWithStateCode200(err_const.ERR_TOKEN_INVALID, err.Error())
		//	return
		//}

		type RegisterParam struct {
			ShopName   string  `json:"shop_name"`
			Province   string  `json:"province"`
			City       string  `json:"city"`
			Area       string  `json:"area"`
			Address    string  `json:"address"`
			Lat        float64 `json:"lat"`
			Lng        float64 `json:"lng"`
			CateId     int64   `json:"cate_id,string"`
			License    string  `json:"license"`
			Mobile     string  `json:"mobile"`
			TenantName string  `json:"tenant_name"`
		}

		//var registerParam = &RegisterParam{
		//	ShopName: string(ctxExt.Peek("shop_name")),
		//	Province: string(ctxExt.Peek("province")),
		//	City:     string(ctxExt.Peek("city")),
		//	Area:     string(ctxExt.Peek("area")),
		//	Address:  string(ctxExt.Peek("address")),
		//	Mobile:   string(ctxExt.Peek("mobile")),
		//	CateId:   utils.BytesToInt64(ctxExt.Peek("cate_id")),
		//	License:  string(ctxExt.Peek("license")),
		//	Lat:      utils.BytesToFloat64(ctxExt.Peek("lat")),
		//	Lng:      utils.BytesToFloat64(ctxExt.Peek("lng")),
		//}

		var registerParam RegisterParam
		requestByte := ctxExt.PostBody()
		err := json.Unmarshal(requestByte, &registerParam)

		if err != nil {
			code = 100
			msg = "参数错误"
			break
		}

		var mainTenantId int64 = 0
		hasTenant := vc.tenantService.GetTenantMemberByUidTidAndRole(appwho)
		if hasTenant == nil {
			//没有主租户 添加主租户
			mainTenant, _, err := vc.tenantService.CreateTenantWithMember(appwho, registerParam.TenantName)
			if err != nil {
				code = 100
				msg = "参数错误"
				break
			}
			mainTenantId = mainTenant.Id
		} else {
			mainTenantId = hasTenant.TenantId
		}

		subTenant, err := vc.tenantService.CreateSubTenant(appwho, mainTenantId)
		if err != nil {
			ctxExt.ResponseWithStateCode200(err_const.ERR_TOKEN_INVALID, err.Error())
			return
		}

		newShop := new(EShop)

		newShop.ShopName = registerParam.ShopName
		newShop.IfCheck = 0
		newShop.Mobile = registerParam.Mobile
		newShop.CateId = registerParam.CateId
		newShop.City = registerParam.City
		newShop.Province = registerParam.Province
		newShop.Area = registerParam.Area
		newShop.Lat = registerParam.Lat
		newShop.Lng = registerParam.Lng
		newShop.Address = registerParam.Address
		newShop.License = registerParam.License
		newShop.TenantId = subTenant.Id

		type RegisterRes struct {
			SubTenantId int64 `json:"sub_tenant_id,string"`
		}

		var res = new(RegisterRes)
		res.SubTenantId = subTenant.Id
		response["data"] = res
		if false == vc.service.SaveEShop(newShop) {
			code = 100
			msg = "false"
			break
		}

		vc.tenantService.UpdateRegisterState(subTenant.Id, common.REG_STATE_SUBMITED)

		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return

}

func (vc *EShopCtrl) GetShopForSelectByTenand(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})

	code := 0
	msg := ""

	sessionData := common.GetSessionData(&ctxExt)
	appwho := sessionData.AppTokenWho
	hasTenant := vc.tenantService.GetTenantById(appwho.TenantId)

	var mainTenantId int64 = appwho.TenantId
	if hasTenant.ParentTenantId > 0 {
		mainTenantId = hasTenant.ParentTenantId
	}

	response["code"] = code
	response["msg"] = msg
	response["data"] = vc.service.ListByTenandId(mainTenantId)
	ctxExt.JSON(200, response)
	return
}

func (vc *EShopCtrl) GetShopForTenand(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})

	code := 0
	msg := ""

	sessionData := common.GetSessionData(&ctxExt)
	appwho := sessionData.AppTokenWho

	response["code"] = code
	response["msg"] = msg
	response["data"] = vc.service.GetEShopByTenantId(appwho.TenantId)
	ctxExt.JSON(200, response)
	return
}

func (vc *EShopCtrl) ModifyShopForTenand(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})

	code := 0
	msg := ""

	for {

		sessionData := common.GetSessionData(&ctxExt)
		appwho := sessionData.AppTokenWho

		type ShopParam struct {
			Id            int64   `json:"id,string"`
			ShopName      string  `json:"shop_name"`
			Province      string  `json:"province"`
			City          string  `json:"city"`
			Area          string  `json:"area"`
			Address       string  `json:"address"`
			Lat           float64 `json:"lat"`
			Lng           float64 `json:"lng"`
			CateId        int64   `json:"cate_id,string"`
			Logo       string  `json:"logo"`
			Mobile        string  `json:"mobile"`
			Banner        string  `json:"banner"`
			Description   string  `json:"description"`
			Recommend     string  `json:"recommend"`
			WorkType      int     `json:"work_type"`
			WorkBeginTime string  `json:"work_begintime"`
			WorkEndTime   string  `json:"work_endtime"`
			WeixinNo      string  `json:"weixin_no"`
			WeixinQrCode  string  `json:"weixin_qrcode"`
			ImagesJson    string  `json:"images_json"`
		}

		var shopParam ShopParam
		requestByte := ctxExt.PostBody()
		err := json.Unmarshal(requestByte, &shopParam)

		if err != nil {
			code = 100
			msg = "参数错误"
			break
		}

		shop := vc.service.GetEShopById(shopParam.Id)
		if shop == nil || shop.TenantId != appwho.TenantId{
			code = 100
			msg = "店铺信息不存在"
			break
		}

		shop.ShopName = shopParam.ShopName
		shop.Province = shopParam.Province
		shop.City = shopParam.City
		shop.Area = shopParam.Area
		shop.Address = shopParam.Address
		shop.Lat = shopParam.Lat
		shop.Lng = shopParam.Lng
		shop.CateId = shopParam.CateId
		shop.Logo = shopParam.Logo
		shop.Mobile = shopParam.Mobile
		shop.Banner = shopParam.Banner
		shop.Description = shopParam.Description
		shop.Recommend = shopParam.Recommend
		shop.WorkType = shopParam.WorkType
		shop.WorkBeginTime = shopParam.WorkBeginTime
		shop.WorkEndTime = shopParam.WorkEndTime
		shop.WeixinNo = shopParam.WeixinNo
		shop.WeixinQrCode = shopParam.WeixinQrCode
		shop.ImagesJson = shopParam.ImagesJson

		if false == vc.service.UpdateEShop(shop) {
			code = 100
			msg = "系统异常"
			break
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return

}
